package com.wsz.bot.service.impl;

import com.wsz.pojo.dto.BotDto;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BotPool extends Thread{

    private final static ReentrantLock lock = new ReentrantLock();

    private final Condition condition = lock.newCondition();//条件变量

    private final Queue<BotDto> bots = new LinkedList<>();

    public void addBot(BotDto botDto){
        lock.lock();
        try{
            bots.add(botDto);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }


    private void consume(BotDto botDto){
        Consumer consumer = new Consumer();
        consumer.startTimeOut(2000,botDto);
    }

    @Override
    public void run() {
        while(true){
            lock.lock();
            if(bots.isEmpty()){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            }else{
                BotDto remove = bots.remove();
                lock.unlock();
                consume(remove);
            }
        }
    }
}
